package com.yonyou.crm.common.json.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.ezmorph.MorphException;
import net.sf.ezmorph.object.AbstractObjectMorpher;

public class CrmDateMorpher extends AbstractObjectMorpher {

	private final static String ClearDate = "0001-01-01 00:00:00";
	
	@Override
	public Object morph(Object value) {
		
		if(value == null){  
		    value = ClearDate;  
		} 
		
		if(Date.class.isAssignableFrom(value.getClass())){  
		    return (Date)value;  
		}
		
		if(!supports(value.getClass())){  
		    throw new MorphException(value.getClass() + " 是不支持的类型");  
		}
		
		if (String.class.isAssignableFrom(value.getClass())) {
			value = value.toString().equals("") ? ClearDate : value;
		}
		String[] formats = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"};
		String strValue = value.toString();  
		SimpleDateFormat sdf = null;
		for(int i=0; i < formats.length; i++){  
		    if(null == sdf){  
		    	sdf = new SimpleDateFormat(formats[i]);  
		    }else{  
		    	sdf.applyPattern(formats[i]);  
		    }  
		    try{  
		        return new Date(sdf.parse(strValue.toLowerCase()).getTime());
		    }  
		    catch (ParseException e) {  
		    }  
		} 
		return null;
	}

	@Override
	public Class<Date> morphsTo() {
		return Date.class;
	}

}
